package com.zmc.third.application.factory.service.alipay;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zmc.common.domain.vo.order.OrderPayInfo;
import com.zmc.common.domain.vo.third.PayRefundVo;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.common.utils.R;
import com.zmc.third.infrastructure.bean.resp.PayChannelResp;
import com.zmc.third.infrastructure.bean.resp.PayNotifyResp;
import com.zmc.third.infrastructure.bean.resp.PayQueryResp;
import com.zmc.third.infrastructure.entity.PaymentInfoEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @Author：zmc
 * @Date：2025/1/10 15:10
 * 电脑网站支付
 */

@Component
public class WebsitePayServiceImpl implements AlipayService {

    public static final Logger log = LoggerFactory.getLogger(WebsitePayServiceImpl.class);

    @Override
    public R requestPayChannel(AlipayClient alipayClient, PaymentInfoEntity paymentInfo, String notifyUrl, String returnUrl) {
        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        // 设置商户订单号
        model.setOutTradeNo(paymentInfo.getTradeSn());
        // 设置订单总金额
        model.setTotalAmount(paymentInfo.getTotalAmount().toString());
        // 设置订单标题
        model.setSubject(paymentInfo.getSubject());
        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置PC扫码支付的方式
        /*model.setQrPayMode("0");*/
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        try {
            // 如果需要返回GET请求，请使用
            // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
            log.info("支付渠道请求结果：{}", JSON.toJSONString(response));
            String pageRedirectionData = response.getBody();
            if (response.isSuccess()) {
                return R.ok(new PayChannelResp(pageRedirectionData, true));
            }
        } catch (AlipayApiException e) {
            log.error("电脑网站支付请求获取支付页面异常", e);
        }
        return R.error("电脑网站支付请求获取支付页面失败");
    }

}
